package com.itheima.reggie.controller;

import com.itheima.reggie.common.CodeEnum;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishAndFlavor;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

@RestController
@RequestMapping("/dish")
@ResponseBody
public class DishController {

    @Autowired
    DishService dishService;

    @PostMapping
    public R saveDish(HttpServletRequest request, @RequestBody DishAndFlavor dish) {
        int code = dishService.selectDishByName(dish.getName());
        if (code == CodeEnum.ERROR_HASENTITY) {
            return R.error("已有同名用户存在");
        }
        dishService.savDish(request, dish);
        return R.success("成功");
    }

    @GetMapping("page")
    public R pageDish(int page, int pageSize, String name) {
        return dishService.pageCategory(page, pageSize, name);
    }

    @GetMapping("/{id}")
    public R<DishAndFlavor> getDishById(@PathVariable("id") Long id) {
        return R.success(dishService.getDishById(id));
    }

    @PutMapping()
    public R updateDish(HttpServletRequest request, @RequestBody DishAndFlavor dish) {
        try {
            dishService.updateDish(request, dish);
        } catch (Exception e) {
            return R.error("已有同名菜品存在");
        }
        return R.success("修改成功");
    }

    @PostMapping("/status/{status}")
    public R updateStatusById(@PathVariable("status") Integer status,Long[] ids){
        dishService.updateStatusById(status,ids);
        return R.success("更新售卖状态成功");
    }

    @DeleteMapping
    public R deleteDish(Long[] ids){
        dishService.deleteDish(ids);
        return R.success("删除成功");
    }
    @GetMapping("/list")
    public R<List<DishAndFlavor>> listCategory(Long categoryId){
        return R.success(dishService.selectListByCategoryId(categoryId));

    }
}
